package cn.zmall.content.service.impl;

import cn.zmall.common.exception.ZmallException;
import cn.zmall.common.jedis.JedisClient;
import cn.zmall.common.pojo.DataTablesResult;
import cn.zmall.common.pojo.TreeNode;
import cn.zmall.content.service.ContentService;
import cn.zmall.manager.dto.DtoUtil;
import cn.zmall.manager.dto.front.AllGoodsResult;
import cn.zmall.manager.dto.front.Product;
import cn.zmall.manager.dto.front.ProductDet;
import cn.zmall.manager.mapper.*;
import cn.zmall.manager.pojo.*;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.awt.peer.PanelPeer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author BinBini
 * @Date 2020/12/12 22:03
 * @Version 1.0
 */
@Service
public class ContentServiceImpl implements ContentService {

    private static final Logger log = LoggerFactory.getLogger(ContentServiceImpl.class);

    @Autowired
    private TbPanelMapper tbPanelMapper;
    @Autowired
    private TbPanelContentMapper tbPanelContentMapper;
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Autowired
    private TbItemCatMapper tbItemCatMapper;
    @Autowired
    private JedisClient jedisClient;

    @Value("PRODUCT_HOME")
    private String PRODUCT_HOME;        // 首页商城缓存
    @Value("PRODUCT_ITEM")
    private String PRODUCT_ITEM;        // 商品详情缓存前缀
    @Value("12000")
    private Integer ITEM_EXPIRE;        // 商品详情缓存过期时间
    @Value("0")
    private Integer HEADER_PANEL_ID;    // 导航栏板块ID
    @Value("HEADER_PANEL")
    private String HEADER_PANEL;        // 导航栏板块缓存key
    @Value("6")
    private int RECOMMEND_PANEL_ID;     // 推荐板块ID
    @Value("RECOMMEND_PANEL")
    private String RECOMMEND_PANEL;     // 推荐板块缓存key

    @Override
    public int addPanelContent(TbPanelContent tbPanelContent) {
        tbPanelContent.setCreated(new Date());
        tbPanelContent.setUpdated(new Date());
        if (tbPanelContentMapper.insert(tbPanelContent) != 1) {
            throw new ZmallException("新增板块内容失败");
        }
        // 同步导航栏缓存
        if (tbPanelContent.getPanelId() == HEADER_PANEL_ID) {
            updateNavListRedis();
        }
        // 同步缓存
        deleteHomeRedis();
        return 1;
    }

    @Override
    public DataTablesResult getPanelContentListByPanelId(int panelId) {
        DataTablesResult result = new DataTablesResult();
        List<TbPanelContent> list = new ArrayList<>();
        TbPanelContentExample example = new TbPanelContentExample();
        TbPanelContentExample.Criteria criteria = example.createCriteria();
        //条件查询
        criteria.andPanelIdEqualTo(panelId);
        list = tbPanelContentMapper.selectByExample(example);
        for (TbPanelContent content : list) {
            if (content.getProductId() != null) {
                TbItem tbItem = tbItemMapper.selectByPrimaryKey(content.getProductId());
                content.setProductName(tbItem.getTitle());
                content.setSalePrice(tbItem.getPrice());
                content.setSubTitle(tbItem.getSellPoint());
            }
        }
        result.setData(list);
        return result;
    }

    @Override
    public int deletePanelContent(int id) {
        if (tbPanelContentMapper.deleteByPrimaryKey(id) != 1) {
            throw new ZmallException("删除板块失败");
        }
        // 同步缓存
        deleteHomeRedis();
        return 1;
    }

    @Override
    public int updatePanelContent(TbPanelContent tbPanelContent) {
        TbPanelContent old = getTbPanelContentById(tbPanelContent.getId());
        if (StringUtils.isBlank(tbPanelContent.getPicUrl())) {
            tbPanelContent.setPicUrl(old.getPicUrl());
        }
        if (StringUtils.isBlank(tbPanelContent.getPicUrl2())) {
            tbPanelContent.setPicUrl2(old.getPicUrl2());
        }
        if (StringUtils.isBlank(tbPanelContent.getPicUrl3())) {
            tbPanelContent.setPicUrl3(old.getPicUrl3());
        }
        tbPanelContent.setCreated(old.getCreated());
        tbPanelContent.setUpdated(new Date());
        if (tbPanelContentMapper.updateByPrimaryKey(tbPanelContent) != 1) {
            throw new ZmallException("更新板块内容失败");
        }
        // 同步导航栏缓存
        if (tbPanelContent.getPanelId() == HEADER_PANEL_ID) {
            updateNavListRedis();
        }
        // 同步缓存
        deleteHomeRedis();
        return 1;
    }

    @Override
    public TbPanelContent getTbPanelContentById(int id) {
        TbPanelContent tbPanelContent = tbPanelContentMapper.selectByPrimaryKey(id);
        if (tbPanelContent == null) {
            throw new ZmallException("通过id获取板块内容失败");
        }
        return tbPanelContent;
    }

    @Override
    public List<TbPanel> getHome() {
        List<TbPanel> list = new ArrayList<>();

        // 查询缓存
        try {
            String json = jedisClient.get(PRODUCT_HOME);
            if (json != null) {
                list = new Gson().fromJson(json, new TypeToken<List<TbPanel>>() {
                }.getType());
                log.info("读取首页缓存");
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 没有缓存
        TbPanelExample example = new TbPanelExample();
        TbPanelExample.Criteria criteria = example.createCriteria();
        criteria.andPositionEqualTo(0);
        criteria.andStatusEqualTo(1);
        example.setOrderByClause("sort_order");
        list = tbPanelMapper.selectByExample(example);
        for (TbPanel tbPanel : list) {
            TbPanelContentExample contentExample = new TbPanelContentExample();
            contentExample.setOrderByClause("sort_order");
            TbPanelContentExample.Criteria contentCriteria = contentExample.createCriteria();
            contentCriteria.andPanelIdEqualTo(tbPanel.getId());
            List<TbPanelContent> contentList = tbPanelContentMapper.selectByExample(contentExample);
            for (TbPanelContent content : contentList) {
                if (content.getProductId() != null) {
                    TbItem tbItem = tbItemMapper.selectByPrimaryKey(content.getProductId());
                    content.setProductName(tbItem.getTitle());
                    content.setSalePrice(tbItem.getPrice());
                    content.setSubTitle(tbItem.getSellPoint());
                }
            }
            tbPanel.setTbPanelContentList(contentList);
        }
        // 把结果添加进缓存中
        try {
            jedisClient.set(PRODUCT_HOME, new Gson().toJson(list));
            log.info("添加进缓存");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<TbPanel> getRecommendGoods() {
        List<TbPanel> list = new ArrayList<>();

        // 查询缓存
        try {
            String json = jedisClient.get(RECOMMEND_PANEL);
            if (json != null) {
                list = new Gson().fromJson(json, new TypeToken<List<TbPanel>>() {
                }.getType());
                log.info("读取了推荐板块缓存");
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        list = getTbPanelAndContentsById(RECOMMEND_PANEL_ID);
        //把结果添加至缓存
        try {
            jedisClient.set(RECOMMEND_PANEL, new Gson().toJson(list));
            log.info("添加了推荐板块缓存");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public ProductDet getProductDet(Long id) {
        // 查询缓存
        try {
            String json = jedisClient.get(PRODUCT_ITEM + ":" + id);
            if (json != null) {
                ProductDet productDet = new Gson().fromJson(json, ProductDet.class);
                log.info("读取了" + id + "详情缓存");
                // 重置缓存时间
                jedisClient.expire(PRODUCT_ITEM + ":" + id, ITEM_EXPIRE);
                return productDet;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        TbItem tbItem = tbItemMapper.selectByPrimaryKey(id);
        ProductDet productDet = new ProductDet();
        productDet.setProductId(id);
        productDet.setProductName(tbItem.getTitle());
        productDet.setSubTitle(tbItem.getSellPoint());
        if (tbItem.getLimitNum() != null && !tbItem.getLimitNum().toString().isEmpty()) {
            productDet.setLimitNum(Long.valueOf(tbItem.getLimitNum()));
        } else {
            productDet.setLimitNum(Long.valueOf(tbItem.getNum()));
        }
        productDet.setSalePrice(tbItem.getPrice());

        TbItemDesc tbItemDesc = tbItemDescMapper.selectByPrimaryKey(id);
        productDet.setDetail(tbItemDesc.getItemDesc());

        if (tbItem.getImage() != null && !tbItem.getImage().isEmpty()) {
            String images[] = tbItem.getImage().split(",");
            productDet.setProductImageBig(images[0]);
            List list = new ArrayList();
            for (int i = 0; i < images.length; i++) {
                list.add(images[i]);
            }
            productDet.setProductImageSmall(list);
        }
        //无缓存 把结果添加至缓存
        try {
            jedisClient.set(PRODUCT_ITEM + ":" + id, new Gson().toJson(productDet));
            //设置过期时间
            jedisClient.expire(PRODUCT_ITEM + ":" + id, ITEM_EXPIRE);
            log.info("添加了商品" + id + "详情缓存");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productDet;
    }

    public List<TbPanel> getTbPanelAndContentsById(Integer panelId) {
        List<TbPanel> list = new ArrayList<>();
        TbPanelExample example = new TbPanelExample();
        TbPanelExample.Criteria criteria = example.createCriteria();
        //条件查询
        criteria.andIdEqualTo(panelId);
        criteria.andStatusEqualTo(1);
        list = tbPanelMapper.selectByExample(example);
        for (TbPanel tbPanel : list) {
            TbPanelContentExample exampleContent = new TbPanelContentExample();
            exampleContent.setOrderByClause("sort_order");
            TbPanelContentExample.Criteria criteriaContent = exampleContent.createCriteria();
            //条件查询
            criteriaContent.andPanelIdEqualTo(tbPanel.getId());
            List<TbPanelContent> contentList = tbPanelContentMapper.selectByExample(exampleContent);
            for (TbPanelContent content : contentList) {
                if (content.getProductId() != null) {
                    TbItem tbItem = tbItemMapper.selectByPrimaryKey(content.getProductId());
                    content.setProductName(tbItem.getTitle());
                    content.setSalePrice(tbItem.getPrice());
                    content.setSubTitle(tbItem.getSellPoint());
                }
            }

            tbPanel.setTbPanelContentList(contentList);
        }
        return list;
    }

    @Override
    public AllGoodsResult getAllProduct(int page, int size, String sort, Long cid, int priceGt, int priceLte) {
        AllGoodsResult allGoodsResult = new AllGoodsResult();
        List<Product> list = new ArrayList<>();

        if (page <= 0) {
            page = 1;
        }
        PageHelper.startPage(page, size);
        String orderCol = "created";
        String orderDir = "desc";
        if (sort.equals("1")) {
            orderCol = "price";
            orderDir = "asc";
        } else if (sort.equals("-1")) {
            orderCol = "price";
            orderDir = "desc";
        } else {
            orderCol = "created";
            orderDir = "desc";
        }

        List<TbItem> tbItemList = tbItemMapper.selectItemFront(cid, orderCol, orderDir, priceGt, priceLte);
        PageInfo<TbItem> pageInfo = new PageInfo<>(tbItemList);
        for (TbItem tbItem : tbItemList) {
            Product product = DtoUtil.TbItemToProduct(tbItem);
            list.add(product);
        }

        allGoodsResult.setList(list);
        allGoodsResult.setTotal((int) pageInfo.getTotal());

        return allGoodsResult;
    }

    @Override
    public String getIndexRedis() {
        try {
            String json = jedisClient.get(PRODUCT_HOME);
            return json;
        } catch (Exception e) {
            log.error(e.toString());
        }
        return "";
    }

    @Override
    public int updateIndexRedis() {
        deleteHomeRedis();
        return 1;
    }

    @Override
    public String getRecommendRedis() {
        try {
            String json = jedisClient.get(RECOMMEND_PANEL);
            return json;
        } catch (Exception e) {
            log.error(e.toString());
        }
        return "";
    }

    @Override
    public int updateRecommendRedis() {
        try {
            jedisClient.del(RECOMMEND_PANEL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    @Override
    public List<TbPanelContent> getNavList() {
        List<TbPanelContent> list = new ArrayList<>();
        //查询缓存
        try {
            //有缓存则读取
            String json = jedisClient.get(HEADER_PANEL);
            if (json != null) {
                list = new Gson().fromJson(json, new TypeToken<List<TbPanelContent>>() {
                }.getType());
                log.info("读取了导航栏缓存");
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        TbPanelContentExample exampleContent = new TbPanelContentExample();
        exampleContent.setOrderByClause("sort_order");
        TbPanelContentExample.Criteria criteriaContent = exampleContent.createCriteria();
        //条件查询
        criteriaContent.andPanelIdEqualTo(HEADER_PANEL_ID);
        list = tbPanelContentMapper.selectByExample(exampleContent);

        //把结果添加至缓存
        try {
            jedisClient.set(HEADER_PANEL, new Gson().toJson(list));
            log.info("添加了导航栏缓存");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public List<TreeNode> getItemCatList(int parentId) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();

        example.setOrderByClause("sort_order");
        criteria.andParentIdEqualTo(new Long(parentId));
        List<TbItemCat> itemCatList = tbItemCatMapper.selectByExample(example);

        List<TreeNode> resultList = new ArrayList<>();

        for (TbItemCat tbItemCat : itemCatList) {
            TreeNode treeNode = DtoUtil.TbItemCatToTreeNode(tbItemCat);

            resultList.add(treeNode);
        }

        return resultList;
    }

    @Override
    public List<TreeNode> getRandomItemCatLsit() {
        TbItemCatExample example = new TbItemCatExample();
        List<TbItemCat> tbItemCatList = tbItemCatMapper.selectByExample(example);
        List<TreeNode> resultList = new ArrayList<>();
        for(int i = 0; i < 16; i++) {
            int randomIndex = new Random().nextInt(tbItemCatList.size() -1);
            TreeNode treeNode = DtoUtil.TbItemCatToTreeNode(tbItemCatList.get(randomIndex));
            resultList.add(treeNode);
        }
        return resultList;
    }

    /**
     * 同步导航栏缓存
     */
    public void updateNavListRedis() {

        try {
            jedisClient.del(HEADER_PANEL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步首页缓存
     */
    public void deleteHomeRedis() {
        try {
            jedisClient.del(PRODUCT_HOME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
